package com.example.paging3samples.di

import android.app.Application
import android.content.Context
import androidx.room.Room
import com.example.paging3samples.database.PostDatabase
import com.example.paging3samples.database.repository.PostRepository
import com.example.paging3samples.network.ApiService
import com.example.paging3samples.network.HeaderInterceptor
import com.example.paging3samples.network.PagingSampleRepo
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {
    @Provides
    @Singleton
    fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor =
        HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)

    @Provides
    @Singleton
    fun provideOkHttpClient(
        @ApplicationContext context: Context,
        httpLoggingInterceptor: HttpLoggingInterceptor
    ): OkHttpClient =
        OkHttpClient.Builder().apply {
            interceptors().add(httpLoggingInterceptor.apply {
//                readTimeout(60L, TimeUnit.SECONDS)
//                connectTimeout(60L, TimeUnit.SECONDS)
//                writeTimeout(60L, TimeUnit.SECONDS)
            })
            interceptors().add(HeaderInterceptor())
        }.build()

    @Provides
    @Singleton
    fun providePostDatabase(app: Application): PostDatabase {
        return Room.databaseBuilder(app, PostDatabase::class.java, "post_db").build()
    }

    @Provides
    @Singleton
    fun providePostRepository(postDatabase: PostDatabase): PostRepository {
        return PostRepository(postDatabase.postDao)
    }

    @Provides
    @Singleton
    fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit =
        Retrofit.Builder().apply {
            baseUrl(ApiService.BASE_URL)
            addConverterFactory(GsonConverterFactory.create(gson))
            client(okHttpClient)
        }.build()

    @Provides
    @Singleton
    fun provideCharacterApi(retrofit: Retrofit): ApiService =
        retrofit.create(ApiService::class.java)

    @Provides
    @Singleton
    fun provideGson(): Gson =
        GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
            .serializeNulls()
            .setLenient()
            .create()

    @Provides
    @Singleton
    fun providePagingSamplePro(apiService: ApiService): PagingSampleRepo =
        PagingSampleRepo(apiService)

}
